package com.remote.common.util;

import com.remote.common.command.Commands;
import com.remote.common.exception.RemoteException;
import com.remote.common.model.Invocation;
import com.remote.common.model.Request;
import com.remote.common.model.Response;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;

public class Utils {

    public static boolean isAvaliable(ChannelHandlerContext ctx) {
        return ctx.channel() != null && ctx.channel().isActive() && ctx.channel().isOpen();
    }

    public static void sendError(Channel channel, Invocation invocation, String e) {
        Response response = new Response();
        response.setIsSucceed(false);
        response.setClientId(invocation.getClientId());
        response.setError(new RemoteException(e));
        response.setValue(e);
        channel.writeAndFlush(response);
    }

    public static void sendData(Channel channel, Invocation invocation) {
        Response response = new Response();
        response.setIsSucceed(true);
        response.setClientId(invocation.getClientId());
        response.setTargetClientId(invocation.getTargetClientId());
        response.setCommand(invocation.getCommand());
        response.setValue(invocation.getValue());
        channel.writeAndFlush(response);
    }

    public static Request buildRequest(String clientId,  Enum<Commands> commands, Object value) {
        Request request = new Request();
        request.setClientId(clientId);
        request.setCommand(commands);
        request.setValue(value);
        return request;
    }

    public static Request buildRequest(String clientId, String targetClientId,  Enum<Commands> commands, Object value) {
        Request request = new Request();
        request.setClientId(clientId);
        request.setTargetClientId(targetClientId);
        request.setCommand(commands);
        request.setValue(value);
        return request;
    }

    public static Response buildResponse(Invocation invocation,  Enum<Commands> commands) {
        return buildResponse(invocation, commands, null);
    }


    public static Response buildResponse(Invocation invocation, Enum<Commands> commands, Object value) {
        Response response = new Response();
        response.setIsSucceed(true);
        response.setClientId(invocation.getClientId());
        response.setTargetClientId(invocation.getTargetClientId());
        response.setCommand(commands);
        response.setValue(value);
        return response;
    }
}
